import axios from 'axios';


export function lastIndexes(params){
    return new Promise((resolve, reject) => {
        axios({
            method: 'get',
            url: '/apis/lastIndexes',
            data: params
        }).then(response => {
            // const processedData = extractAndTransform(response.data);
            // console.log(response.data)
            resolve(response.data);
        }).catch(error => {
            reject(error);
        });
    });
}


export function lastCpuUsage(params){
    return new Promise((resolve, reject) => {
        axios({
            method: 'get',
            url: '/apis/lastCpuUsage',
            data: params
        }).then(response => {
            const data = response.data.data.map(v=>{
                return {
                    eventTime: v.eventTime,
                    hostName: v.hostName,
                    cpuId: v.cpuId,
                    usagePercent: v.usagePercent
                }
            })
            console.log("lastCpuUsage",data)
            resolve(data);
        }).catch(error => {
            reject(error);
        });
    });
}


export function getindexsByTimes(params){
    console.log("params",params)
    return new Promise((resolve, reject) => {
        axios({
            method: 'get',
            url: '/apis/getindexsByTimes',
            params: params
        }).then(response => {
            // debugger
            // console.log("111",response.data)
            resolve(getindexsByTimesProcessResponseData(response.data.data.serverData));
        }).catch(error => {
            reject(error);
        });
    });
}

function getindexsByTimesProcessResponseData(data) {
    const result = {};
    // debugger
    data.forEach(item => {
        console.log("111", item)
        const deviceName = item.hostName;
        if (!result[deviceName]) {
            result[deviceName] = [];
        }
        const formattedTime = new Date(item.eventTime).toLocaleString().replace('T', ' ').substring(0, 19);
        result[deviceName].push({
            Time: item.eventTime,
            Device: item.hostName,
            total_cpu_usage: item.totalCPUUsage,
            mem_used_percent: item.memUsedPercent,
            TimeStr: formattedTime
        });
    });
    
    // 按 Time 升序排序
    for (const deviceName in result) {
        result[deviceName].sort((a, b) => new Date(a.Time) - new Date(b.Time));
    }
    
    return result;
}

